<template>
  <div>
    <el-dialog :title="title" :visible.sync="visible" @closed="clearHandle">
      <el-form ref="form" :rules="rules" :model="form">
        <el-form-item
          prop="name"
          label="角色名称"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item
          prop="description"
          label="角色描述"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.description" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addRole, editRoleById } from '../../../api/setting'
export default {
  name: 'SettingDialog',
  data() {
    return {
      visible: false,
      form: {
        name: '',
        description: ''
      },
      formLabelWidth: '120px',
      rules: {
        name: [
          {
            required: true,
            message: '角色名不能为空',
            targgle: 'blur'
          }
        ],
        description: [
          {
            required: true,
            message: '角色描述不能为空',
            targgle: 'blur'
          }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.form.id ? '修改信息' : '新增信息'
    }
  },
  methods: {
    clearHandle() {
      this.form = {
        name: '',
        description: ''
      }
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    addRoles() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          if (this.form.id) {
            await editRoleById(this.form)
            this.$message.success('修改成功')
          } else {
            await addRole(this.form)
            this.$message.success('新增成功')
          }
          this.visible = false
          this.form = {
            name: '',
            description: ''
          }
          this.$parent.getData()
        } else {
          this.$message.error('格式有误,请检查!')
          return false
        }
      })
    }
  }
}
</script>

<style></style>
